/* jshint esversion: 6 */
const Router = require('koa-router');
const tool = require("../../tools/tool");
const router = new Router();
const {db, Op, QueryTypes} = require("../../models/db");
// 修改密码

router.post('/user/list', async ctx => {
    let tenantId = ctx.user.tenantId;
    let formData = ctx.request.body.formData
    let body = ctx.request.body
    let username = formData.username
    let name = formData.name
    let mobile = formData.mobile
    let sql = `select * from v_users where tenantId = ${tenantId}  `
    let currentPage = body.currentPage?body.currentPage:1;
    let pageSize = body.pageSize?body.pageSize:200;
    let offset = (currentPage-1) * pageSize;
    let excel = body.excel
    if(mobile) {
        sql += ` and mobile like '%${mobile}%' `
    }
    if(name) {
        sql += ` and name like '%${name}%' `
    }
    if(username) {
        sql += ` and username like '%${username}%' `
    }
    if(excel) {
        sql += ` order by id `
        let list = await db.query(sql, {type: QueryTypes.SELECT})
        return tool.doExcelOut(ctx, list)
    }
    else {
        let sort = tool.getSort(ctx)
        let sorts = ' id '
        if(sort) sorts = sort
        let totalModel = await db.query(`select count(*) total from (${sql}) a `, {type: QueryTypes.SELECT, plain: true})
        sql = ` select * from (${sql}) a order by ${sorts} offset ${offset} rows fetch next ${pageSize} rows only;`
        let list = await db.query(sql, {type: QueryTypes.SELECT})
        return ctx.suc('', {
            total: totalModel?totalModel.total: 0,
            list: list
        })
    }
})



module.exports = router;